/**
 * 将动态生成的题目转换为静态题目
 * 这样可以进行验证和人工检查
 */

const fs = require('fs');
const path = require('path');

const ROOT = path.join(__dirname, '..', '..');

// 需要转换的文件列表
const 动态文件列表 = [
  'questions/middle-school/回归分析.ts',
  'questions/middle-school/实际应用.ts',
  'questions/middle-school/数学建模.ts',
  'questions/middle-school/竞赛基础.ts',
  'questions/middle-school/综合压轴题.ts'
];

function 转换文件(filePath) {
  console.log(`\n🔄 转换文件: ${filePath}`);

  const fullPath = path.join(ROOT, filePath);
  const content = fs.readFileSync(fullPath, 'utf-8');

  // 直接在当前进程中执行代码
  try {
    // 使用eval执行代码并获取结果
    const code = content
      .replace(/export const /g, 'var ')
      .replace(/export default /g, 'var result = ');

    // 创建一个安全的执行环境
    const questionsArray = eval(`
      (function() {
        ${code}
        // 返回第一个定义的变量
        if (typeof result !== 'undefined') return result;
        const vars = Object.keys(this).filter(k => k.includes('QUESTIONS'));
        return vars.length > 0 ? this[vars[0]] : [];
      }).call({})
    `);

    console.log(`✅ 成功加载 ${questionsArray.length} 题`);

    // 生成静态代码
    const 题型名 = path.basename(filePath, '.ts');
    let staticCode = `// ${题型名} - 初中数学综合题型（50题）\n`;
    staticCode += `// 已从动态生成转换为静态题目，便于验证和检查\n\n`;
    staticCode += `interface Question {\n`;
    staticCode += `  stem: string;\n`;
    staticCode += `  difficulty: number;\n`;
    staticCode += `  answer: (string | number)[];\n`;
    staticCode += `  hint1: string;\n`;
    staticCode += `  hint2: string;\n`;
    staticCode += `  solution: string;\n`;
    staticCode += `}\n\n`;
    staticCode += `export const ${题型名}_QUESTIONS: Question[] = [\n`;

    questionsArray.forEach((q, i) => {
      const answerStr = Array.isArray(q.answer)
        ? `[${q.answer.map(a => typeof a === 'number' ? a : `"${String(a).replace(/"/g, '\\"')}"`).join(', ')}]`
        : `["${q.answer}"]`;

      staticCode += `  {\n`;
      staticCode += `    stem: "${String(q.stem).replace(/"/g, '\\"').replace(/\n/g, '\\n')}",\n`;
      staticCode += `    difficulty: ${q.difficulty},\n`;
      staticCode += `    answer: ${answerStr},\n`;
      staticCode += `    hint1: "${String(q.hint1).replace(/"/g, '\\"').replace(/\n/g, '\\n')}",\n`;
      staticCode += `    hint2: "${String(q.hint2).replace(/"/g, '\\"').replace(/\n/g, '\\n')}",\n`;
      staticCode += `    solution: "${String(q.solution).replace(/"/g, '\\"').replace(/\n/g, '\\n')}"\n`;
      staticCode += `  }${i < questionsArray.length - 1 ? ',' : ''}\n`;
    });

    staticCode += `];\n\n`;
    staticCode += `export default ${题型名}_QUESTIONS;\n`;

    // 备份原文件
    const backupPath = fullPath.replace('.ts', '.dynamic-backup.ts');
    fs.copyFileSync(fullPath, backupPath);
    console.log(`📦 原文件已备份到: ${backupPath}`);

    // 写入新文件
    fs.writeFileSync(fullPath, staticCode, 'utf-8');
    console.log(`✅ 已转换为静态题目`);

    return { success: true, count: questionsArray.length };
  } catch (error) {
    console.error(`❌ 转换失败: ${error.message}`);
    console.error(error.stack);
    return { success: false, error: error.message };
  }
}

function main() {
  console.log('🚀 开始转换动态生成的题目为静态题目...\n');
  console.log('这样可以：');
  console.log('1. 进行数学验证');
  console.log('2. 人工检查准确性');
  console.log('3. 确保题目质量\n');
  
  const results = [];
  
  for (const file of 动态文件列表) {
    const result = 转换文件(file);
    results.push({ file, ...result });
  }
  
  console.log('\n' + '='.repeat(60));
  console.log('📊 转换统计：');
  console.log('='.repeat(60));
  
  const 成功数 = results.filter(r => r.success).length;
  const 失败数 = results.filter(r => !r.success).length;
  const 总题数 = results.reduce((sum, r) => sum + (r.count || 0), 0);
  
  console.log(`成功转换: ${成功数}个文件`);
  console.log(`转换失败: ${失败数}个文件`);
  console.log(`总题目数: ${总题数}题`);
  console.log('='.repeat(60));
  
  if (失败数 > 0) {
    console.log('\n❌ 失败的文件：');
    results.filter(r => !r.success).forEach(r => {
      console.log(`  - ${r.file}: ${r.error}`);
    });
  }
  
  console.log('\n✅ 转换完成！');
  console.log('📝 原动态文件已备份为 .dynamic-backup.ts');
  console.log('🔍 现在可以运行验证脚本检查题目准确性');
}

main();

